import { PublishLaya2Base } from "./PublishLaya2Base";
import { IPublishVo, IProjectVo } from "../data/Config";
import { existsSync, readFileSync, writeFileSync, readdirSync } from "fs";
import { cpFile } from "../utils/FileUtil";
let path = require("path");

export class XiaoMiPublish extends PublishLaya2Base {
    get projDir() { return "xmgame"; }
    get libJs() { return "laya.xmmini.js"; }
    private _isDebug: boolean;
    init(publishVo: IPublishVo, projectInfo: IProjectVo) {
        super.init(publishVo, projectInfo);
        this._isDebug = !this._publishVo.content.chkRelease;
    }

    async createProject() {
        let isProjExist = existsSync(this.mProjPath + "/node_modules") && existsSync(this.mProjPath + "/sign");
        if (isProjExist) {
            //不需要创建项目
            await this.doPack();
            return;
        }
        this.log("开始创建小米项目，请耐心等待(预计需要10分钟)...");
        await this.exec(`npx create-quickgame ${this.projDir} path=${this.mOutPath} rebuild=true`, { shell: true });
        await this.doPack();
    }

    async doPack() {
        await this.copyDir(this.mTempProjPath, this.mProjPath);
        await this.buildProject();
        await this._copyIcon();
        await this._copySign();
        this._createMainFast();
        await this._buildRpk();
        this.packOver();
    }

    private async _copyIcon() {
        this.log("复制icon");
        if (this._publishVo.content && this._publishVo.content.icon) {
            cpFile(this._publishVo.content.icon, path.join(this.mProjPath, "layaicon", path.basename(this._publishVo.content.icon)));
        }
    }

    private async _copySign() {
        this.log("复制签名");
        if (!this._isDebug) {
            if (this._publishVo.content && this._publishVo.content.cert) {
                await this.copyDir(this._publishVo.content.cert, path.join(this.mProjPath, "sign\/release"));
            } else {
                this.log("正式版秘钥不能为空");
            }
        }
    }

    private _createMainFast() {
        // 修改manifest.json文件
        let manifestPath = path.join(this.mProjPath, "manifest.json");
        if (!existsSync(manifestPath)) {
            return;
        }
        let manifestContent = readFileSync(manifestPath, "utf8");
        let manifestJson = JSON.parse(manifestContent);
        manifestJson.package = this._publishVo.content.appId;
        manifestJson.name = this.mProjectInfo.name;
        // manifestJson.orientation = config.vivoInfo.orientation;
        manifestJson.config.logLevel = this._isDebug ? "debug" : "off";
        // manifestJson.deviceOrientation = config.vivoInfo.orientation;
        manifestJson.versionName = this._version;
        manifestJson.versionCode = this._publishVo.content.versionCode;
        manifestJson.minPlatformVersion = this._publishVo.content.minSdkVersion || "1050";
        manifestJson.icon = `/layaicon/${path.basename(this._publishVo.content.icon)}`;
        delete manifestJson.subpackages;

        writeFileSync(manifestPath, JSON.stringify(manifestJson, null, 4), "utf8");
        // 修改main.js文件
        let mainJsCon = `require("./qg-adapter.js");\nrequire("./libs/${this.libJs}");\nwindow.config=require("./config.js");\nrequire("./index.js");`;
        let mainJsPath = path.join(this.mProjPath, "main.js");
        writeFileSync(mainJsPath, mainJsCon, "utf8");

        // 小米项目，修改index.js
        let filePath = path.join(this.mProjPath, "index.js");
        if (!existsSync(filePath)) {
            return;
        }
        let fileContent = readFileSync(filePath, "utf8");
        fileContent = fileContent.replace(/loadLib(\(['"])/gm, "require$1./");
        writeFileSync(filePath, fileContent, "utf8");
    }

    private async _buildRpk() {
        if (this._isDebug) {
            await this.exec("npm run build", { cwd: this.mProjPath });
        } else {
            await this.exec("npm run release", { cwd: this.mProjPath });
        }
    }

    showPreView() {
        let reg = new RegExp(/((?:http:\/\/)(?:.[\w]+)+)/g);
        let cp = this.spawn("npm.cmd", ["run", "server"], { cwd: this.mProjPath }, (log: string) => {
            let result = reg.exec(log);
            if (result) {
                this.update({
                    url: result, pid: cp.pid, onClose: () => {
                        this.exec("taskkill /pid " + cp.pid + " /f /t");
                    }
                });
            }
        });
    }
}